﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CSKLiteWindowsPhone.WebsiteData;
using System.IO.IsolatedStorage;
using CSKLiteWindowsPhone.Common;
using SQLiteClient;
using Coding4Fun.Phone.Controls;
namespace CSKLiteWindowsPhone
{
    public partial class MainPage : PhoneApplicationPage
    {
        SQLiteConnection _db = null;
        private WebsiteDataSoapClient _websiteDataClient = Utility.GetWebsiteDataSoapClient();
        private string _token = string.Empty;
        private string _userName = string.Empty;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this._db = Utility.GetConnection();
            this._token = IsolatedStorageSettings.ApplicationSettings[Constants.LoginTockenKey] as string;
            this._userName = IsolatedStorageSettings.ApplicationSettings[Constants.LoginUserNameKey] as string;
            if (!string.IsNullOrEmpty(this._token))
            {
                this.GetTestData();
            }
            else
            {
            }
        }

        protected override void OnRemovedFromJournal(System.Windows.Navigation.JournalEntryRemovedEventArgs e)
        {
            base.OnRemovedFromJournal(e);

            this._db.Dispose();
            this._db = null;
        }

        private void GetTestData()
        {
            this.GetTestCases();
            this.GetTestProcs();

            this.MaintainTestSession();
            this.MaintainTestSessionResult();
            this.MaintainProxy();
        }

        private void GetTestSessionResults()
        {
        }

        private void GetTestResults()
        {
        }

        private void GetTestSessions()
        {
        }

        private void GetTestProcs()
        {
            this._websiteDataClient.GetTestProceduresAsync(this._token, this._userName);
            this._websiteDataClient.GetTestProceduresCompleted += new EventHandler<GetTestProceduresCompletedEventArgs>(_websiteDataClient_GetTestProceduresCompleted);
        }

        void _websiteDataClient_GetTestProceduresCompleted(object sender, GetTestProceduresCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                TestProceduresResponse resposne = e.Result;

                this.MaintainTestProcedures(resposne.TestProcedures);
            }
        }

        private void GetTestCases()
        {
            this._websiteDataClient.GetTestCasesAsync(this._token, this._userName);
            this._websiteDataClient.GetTestCasesCompleted += new EventHandler<GetTestCasesCompletedEventArgs>(_websiteDataClient_GetTestCasesCompleted);      
        }

        void _websiteDataClient_GetTestCasesCompleted(object sender, GetTestCasesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                TestCasesResponse resposne = e.Result;
                this.MaintainTestCases(resposne.TestCases);
            }
        }

        private void MaintainTestCases(TestCase[] cases)
        {
            if (this._db != null)
            {

                string sql = @"
CREATE TABLE IF NOT EXISTS TestCase (Id INTEGER PRIMARY KEY,
Type text,
Category text,
InputType text,
Input text,
ProcedureCode int,
Source text,
Description text,
ThreadScope text,
Ace text,
PageIdentificationType text,
PageIdentification text)";
                SQLiteCommand cmd = this._db.CreateCommand(sql);
                int i = cmd.ExecuteNonQuery();

                cmd = this._db.CreateCommand("DELETE FROM TestCase");
                cmd.ExecuteNonQuery();

                foreach (var item in cases)
                {
                    sql = string.Format(@"INSERT INTO TestCase(Id,
Type, 
Category ,
InputType ,
Input ,
ProcedureCode ,
Source ,
Description ,
ThreadScope ,
Ace ,
PageIdentificationType ,
PageIdentification ) VALUES('{11}', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}')",
item.Type,
item.Category,
item.InputType,
item.Input,
item.ProcedureCode,
item.TestSource,
item.Description,
item.ThreatScope,
item.Ace,
string.Empty,
string.Empty,
item.Id);
                    cmd = this._db.CreateCommand(sql);
                    cmd.ExecuteNonQuery();
                }

                cmd = this._db.CreateCommand("select * from TestCase");
                IEnumerable<TestCase> tests = cmd.ExecuteQuery<TestCase>();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.tntileTestCases.Content = tests.Count();
                });
            }
        }

        private void MaintainTestProcedures(TestProcedure[] procs)
        {
            if (this._db != null)
            {

                string sql = @"
CREATE TABLE IF NOT EXISTS TestProcedure (Id INTEGER PRIMARY KEY,
Code text,
Sequence text,
[Group] text,
ParameterType text,
Parameter text,
ResultCode text)";
                SQLiteCommand cmd = this._db.CreateCommand(sql);
                int i = cmd.ExecuteNonQuery();

                cmd = this._db.CreateCommand("DELETE FROM TestProcedure");
                cmd.ExecuteNonQuery();

                foreach (var item in procs)
                {
                    sql = string.Format(@"INSERT INTO TestProcedure(
Id,
Code,
Sequence,
[Group],
ParameterType,
Parameter,
ResultCode) VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')",
item.Id,
item.Code,
item.Sequence,
item.Group,
item.ParameterType,
item.Parameter,
item.ResultCode);
                    cmd = this._db.CreateCommand(sql);
                    cmd.ExecuteNonQuery();
                }

                cmd = this._db.CreateCommand("SELECT * FROM TestProcedure");
                IEnumerable<TestProcedure> tests = cmd.ExecuteQuery<TestProcedure>();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.tntileTestProcedures.Content = tests.Count();
                });
            }

        }

        private void MaintainTestSession()
        {
            if (this._db != null)
            {

                string sql = @"
CREATE TABLE IF NOT EXISTS TestSession (Id text ,
Time text,
Association text,
AssociationValue text,
SessionResultUploaded INTEGER)";
                SQLiteCommand cmd = this._db.CreateCommand(sql);
                int i = cmd.ExecuteNonQuery();

                cmd = this._db.CreateCommand("SELECT * FROM TestSession");
                IEnumerable<DetailedResult> tests = cmd.ExecuteQuery<DetailedResult>();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.tntileTestSessions.Content = tests.Count();
                });
            }
        }

        private void MaintainTestSessionResult()
        {
            if (this._db != null)
            {

                string sql = @"
CREATE TABLE IF NOT EXISTS TestSessionResult (SessionId text,
TestId text,
Squence text,
Code text,
Type text,
TypeValue text,
Type2 text,
Type2Value text)";
                SQLiteCommand cmd = this._db.CreateCommand(sql);
                int i = cmd.ExecuteNonQuery();


                cmd = this._db.CreateCommand("SELECT * FROM TestSessionResult");
                IEnumerable<TestSession> tests = cmd.ExecuteQuery<TestSession>();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.tntileTestSessionResults.Content = tests.Count();
                });
            }

        }

        private void MaintainProxy()
        {

            if (this._db != null)
            {

                string sql = @"
CREATE TABLE IF NOT EXISTS Proxy (
Name text primary key,
ServerPort text,
UserNamePassword text)";
                SQLiteCommand cmd = this._db.CreateCommand(sql);
                int i = cmd.ExecuteNonQuery();

                cmd = this._db.CreateCommand("DELETE FROM Proxy");
                cmd.ExecuteNonQuery();

                List<Proxy> proxies = new List<Proxy>(){
                    new Proxy(){Name="BlueCoat", ServerPort="10.34.51.123:8080", UserNamePassword=string.Empty},
                    new Proxy(){Name="McAfee", ServerPort="10.34.51.123:8080", UserNamePassword=string.Empty},
                    new Proxy(){Name="Cisco", ServerPort="10.34.51.123:8080", UserNamePassword=string.Empty},
                };

                foreach (var item in proxies)
                {
                    sql = string.Format(@"INSERT INTO Proxy(Name,
ServerPort, 
UserNamePassword) VALUES('{0}', '{1}', '{2}')",
item.Name,
item.ServerPort,
item.UserNamePassword);
                    cmd = this._db.CreateCommand(sql);
                    cmd.ExecuteNonQuery();
                }

                cmd = this._db.CreateCommand("select * from Proxy");
                IEnumerable<Proxy> tests = cmd.ExecuteQuery<Proxy>();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.tntileProxyConfig.Content = tests.Count();
                });
            }
        }

        private void tileRunTest_Click(object sender, RoutedEventArgs e)
        {
            Tile tile = sender as Tile;
            string uri = string.Empty;
            if (tile != null)
            {
                switch (tile.Name)
                {
                    case "tileRunTest":
                        uri = "/RunTest.xaml";
                        break;
                    case "tileTestResults":
                        uri = "/TestResults.xaml";
                        break;
                    case "tileTestCases":
                        uri = "/TestCases.xaml";
                        break;
                    case "tileTestProcedures":
                        uri = "/TestProcedures.xaml";
                        break;
                    case "tileTestSessions":
                        uri = "/TestSessions.xaml";
                        break;
                    case "tileTestSessionResults":
                        uri = "/TestSessionResults.xaml";
                        break;
                    case "tileProxyConfig":
                        uri = "/ProxyConfig.xaml";
                        break;
                }
            }

            NavigationService.Navigate(new Uri(uri, UriKind.Relative));
        }

        private void btnSettings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }
    }
}